﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FilesExplorer.Components
{
    internal class FileListView
    {
        ListView listView1;
        ContextMenuStrip contextMenu;

        private string copiedFilePath;
        private string currentFolderPath;

        private ImageList largeImageList;
        private ImageList smallImageList;

        public event Action<string, string> FolderRenamed;
        public event Action Refreshed;
        public event Action<string> FolderSearched;

        public FileListView(ListView listView)
        {
            listView1 = listView;
            InitializeListView();
            InitializeContextMenu();
        }

        private void InitializeListView()
        {
            listView1.View = View.Details; // 设置为详细信息视图
            listView1.FullRowSelect = true; // 支持整行选择
            listView1.Columns.Add("名称", 200); // 添加列
            listView1.Columns.Add("类型", 100);
            listView1.Columns.Add("大小", 100);
            listView1.MouseDoubleClick += ListView1_MouseDoubleClick; // 绑定双击事件
            listView1.MouseUp += ListView1_MouseUp; // 绑定右键菜单事件

            // 初始化 ImageList
            largeImageList = new ImageList();
            largeImageList.ImageSize = new Size(32, 32); // 设置大图标大小

            smallImageList = new ImageList();
            smallImageList.ImageSize = new Size(16, 16); // 设置小图标大小

            listView1.LargeImageList = largeImageList;
            listView1.SmallImageList = smallImageList;
        }

        private void InitializeContextMenu()
        {
            contextMenu = new ContextMenuStrip();
            ToolStripMenuItem createItem = new ToolStripMenuItem("新建");
            ToolStripMenuItem openItem = new ToolStripMenuItem("打开");
            ToolStripMenuItem copyMenuItem = new ToolStripMenuItem("复制");
            ToolStripMenuItem pasteMenuItem = new ToolStripMenuItem("粘贴");
            ToolStripMenuItem renameItem = new ToolStripMenuItem("重命名");
            ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem("删除");
            ToolStripMenuItem switchViewModeItem = new ToolStripMenuItem("切换视图模式");
            ToolStripMenuItem propertyMenuItem = new ToolStripMenuItem("属性");
            ToolStripMenuItem refreshMenuItem = new ToolStripMenuItem("刷新");

            // 新建子菜单：文件夹、文本文件
            ToolStripMenuItem createFolderItem = new ToolStripMenuItem("文件夹");
            ToolStripMenuItem createFileItem = new ToolStripMenuItem("文件");
            createItem.DropDownItems.Add(createFolderItem);
            createItem.DropDownItems.Add(createFileItem);

            createFileItem.Click += CreateFileItem_Click;
            createFolderItem.Click += CreateFolderItem_Click;
            openItem.Click += OpenItem_Click;
            copyMenuItem.Click += CopyMenuItem_Click;
            pasteMenuItem.Click += PasteMenuItem_Click;
            renameItem.Click += RenameItem_Click;
            deleteMenuItem.Click += DeleteMenuItem_Click;
            switchViewModeItem.Click += SwitchViewModeItem_Click;
            propertyMenuItem.Click += PropertyMenuItem_Click;
            refreshMenuItem.Click += RefreshMenuItem_Click;

            contextMenu.Items.Add(createItem);
            contextMenu.Items.Add(openItem);
            contextMenu.Items.Add(copyMenuItem);
            contextMenu.Items.Add(pasteMenuItem);
            contextMenu.Items.Add(renameItem);
            contextMenu.Items.Add(deleteMenuItem);
            contextMenu.Items.Add(switchViewModeItem);
            contextMenu.Items.Add(propertyMenuItem);
            contextMenu.Items.Add(refreshMenuItem);
        }

        public void ListView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var focusedItem = listView1.FocusedItem;
                if (focusedItem != null && focusedItem.Bounds.Contains(e.Location))
                {
                    contextMenu.Show(Cursor.Position);
                }
            }
        }

        public void OpenItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString();

                try
                {
                    if (File.Exists(path))
                    {
                        string extension = Path.GetExtension(path).ToLower();
                        if (extension == ".exe")
                        {
                            // 双击exe文件直接运行
                            Process.Start(path);
                        }
                        else if (extension == ".txt")
                        {
                            // 双击txt文件通过记事本打开
                            Process.Start("notepad.exe", path);
                        }
                    }
                    else if (Directory.Exists(path))
                    {
                        // 如果双击的是文件夹，则加载该文件夹中的内容
                        LoadFilesInListView(path);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("打开失败: " + ex.Message);
                }
            }
        }

        public void CopyMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString();

                if (File.Exists(path))
                {
                    copiedFilePath = path; // 保存被复制文件的路径
                }
            }
        }

        public void PasteMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(copiedFilePath) && Directory.Exists(currentFolderPath))
            {
                string fileName = Path.GetFileName(copiedFilePath);
                string destPath = Path.Combine(currentFolderPath, fileName);

                try
                {
                    if (File.Exists(destPath))
                    {
                        MessageBox.Show("目标文件已存在");
                    }
                    else
                    {
                        File.Copy(copiedFilePath, destPath);
                        LoadFilesInListView(currentFolderPath); // 重新加载文件列表
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("粘贴失败: " + ex.Message);
                }
            }
        }

        public void DeleteMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString();

                try
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                        LoadFilesInListView(currentFolderPath); // 重新加载文件列表
                    }
                    else if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true); // 递归删除文件夹
                        LoadFilesInListView(currentFolderPath); // 重新加载文件列表
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除失败: " + ex.Message);
                }
            }
        }

        public void CreateFolderItem_Click(object sender, EventArgs e)
        {
            string folderName = "新建文件夹";
            string folderPath = Path.Combine(currentFolderPath, folderName);

            try
            {
                Directory.CreateDirectory(folderPath);
                LoadFilesInListView(currentFolderPath); // 重新加载文件列表
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建文件夹失败: " + ex.Message);
            }
        }

        public void CreateFileItem_Click(object sender, EventArgs e)
        {
            string fileName = "新建文件.txt";
            string filePath = Path.Combine(currentFolderPath, fileName);

            try
            {
                File.Create(filePath).Close();
                LoadFilesInListView(currentFolderPath); // 重新加载文件列表
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建文件失败: " + ex.Message);
            }
        }

        public void RenameItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString();

                string newName = Microsoft.VisualBasic.Interaction.InputBox("请输入新的名称", "重命名", Path.GetFileName(path));
                if (!string.IsNullOrEmpty(newName))
                {
                    string newPath = Path.Combine(currentFolderPath, newName);

                    try
                    {
                        if (File.Exists(path))
                        {
                            File.Move(path, newPath);
                        }
                        else if (Directory.Exists(path))
                        {
                            Directory.Move(path, newPath);
                        }

                        LoadFilesInListView(currentFolderPath); // 重新加载文件列表

                        FolderRenamed?.Invoke(path, newPath); // 通知TreeView更新
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("重命名失败: " + ex.Message);
                    }
                }
            }
        }

        public void SwitchViewModeItem_Click(object sender, EventArgs e)
        {
            if (listView1.View == View.Details)
            {
                SwitchViewMode(View.LargeIcon);
            }
            else if (listView1.View == View.LargeIcon)
            {
                SwitchViewMode(View.SmallIcon);
            }
            else if (listView1.View == View.SmallIcon)
            {
                SwitchViewMode(View.List);
            }
            else if (listView1.View == View.List)
            {
                SwitchViewMode(View.Details);
            }
        }

        public void PropertyMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString(); // 获取选中项的完整路径

                try
                {
                    FileProperties.ShowFileProperties(path); // 打开属性页面
                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法显示属性: " + ex.Message);
                }
            }
        }

        public void RefreshMenuItem_Click(object sender, EventArgs e)
        {
            LoadFilesInListView(currentFolderPath); // 重新加载文件列表

            Refreshed?.Invoke(); // 通知TreeView更新
        }


        public void OnFolderSelected(string folderPath)
        {
            currentFolderPath = folderPath;
            LoadFilesInListView(folderPath); // 加载文件
        }

        private void LoadFilesInListView(string path)
        {
            try
            {
                listView1.Items.Clear(); // 清除之前的文件显示
                largeImageList.Images.Clear(); // 清除之前的图标
                smallImageList.Images.Clear(); // 清除之前的图标

                // 获取该目录下的所有文件和子文件夹
                string[] directories = Directory.GetDirectories(path);
                string[] files = Directory.GetFiles(path);

                // 加载默认文件夹图标
                Bitmap folderBitmap = new Bitmap("folder.png");
                Icon defaultFolderIcon = Icon.FromHandle(folderBitmap.GetHicon());

                // 显示文件夹
                foreach (string directory in directories)
                {
                    ListViewItem item = new ListViewItem(Path.GetFileName(directory));
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(""); // 文件夹不显示大小
                    item.Tag = directory; // 记录完整路径

                    // 使用默认文件夹图标
                    largeImageList.Images.Add(defaultFolderIcon);
                    smallImageList.Images.Add(defaultFolderIcon);
                    item.ImageIndex = largeImageList.Images.Count - 1;

                    listView1.Items.Add(item);
                }

                // 显示文件
                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);

                    ListViewItem item = new ListViewItem(fileInfo.Name);
                    item.SubItems.Add(fileInfo.Extension); // 文件类型
                    item.SubItems.Add(fileInfo.Length.ToString() + " B"); // 文件大小
                    item.Tag = file; // 记录完整路径

                    // 获取文件图标
                    Icon fileIcon = Icon.ExtractAssociatedIcon(file);
                    largeImageList.Images.Add(fileIcon);
                    smallImageList.Images.Add(fileIcon);
                    item.ImageIndex = largeImageList.Images.Count - 1;

                    listView1.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 处理没有权限访问的文件夹
                MessageBox.Show("访问权限异常");
            }
        }

        public void Search(string name)
        {
            // 通过名称搜索当前文件夹下的文件和文件夹
            // 若搜索到，则：
            //   如果是文件夹，则展开文件夹，通知FileTreeView选中该文件夹
            //   如果是文件，则选中该文件
            // 若未搜索到，则MessageBox提示未找到

            bool found = false;
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Text == name)
                {
                    found = true;
                    item.Selected = true;
                    listView1.EnsureVisible(item.Index);

                    if (Directory.Exists(item.Tag.ToString()))
                    {
                        FolderSearched?.Invoke(item.Tag.ToString());
                    }

                    break;
                }
            }

            if (!found)
            {
                MessageBox.Show("未找到: " + name);
            }
        }

        private void ListView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selectedItem = listView1.SelectedItems[0];
                string path = selectedItem.Tag.ToString();

                if (File.Exists(path))
                {
                    string extension = Path.GetExtension(path).ToLower();
                    if (extension == ".exe")
                    {
                        // 双击exe文件直接运行
                        Process.Start(path);
                    }
                    else if (extension == ".txt")
                    {
                        // 双击txt文件通过记事本打开
                        Process.Start("notepad.exe", path);
                    }
                }
                else if (Directory.Exists(path))
                {
                    // 如果双击的是文件夹，则加载该文件夹中的内容
                    LoadFilesInListView(path);
                }
            }
        }

        public void SwitchViewMode(View viewMode)
        {
            listView1.View = viewMode; // 切换视图模式
        }


    }
}
